from app.utils.mongo import db
from datetime import datetime
import bcrypt  # 用于密码加密，需安装：pip install bcrypt

class Admin:
    collection = db.admins  # MongoDB集合名

    @classmethod
    def create_admin(cls, username: str, password: str, role: str = "admin"):
        """创建管理员（首次使用需手动调用或在数据库插入）"""
        # 密码加密
        hashed_pwd = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
        admin_data = {
            "username": username,
            "password": hashed_pwd,  # 存储加密后的密码
            "role": role,  # 角色：super_admin/admin
            "created_at": datetime.now()
        }
        return cls.collection.insert_one(admin_data).inserted_id

    @classmethod
    def verify_login(cls, username: str, password: str):
        """验证管理员登录"""
        admin = cls.collection.find_one({"username": username})
        if not admin:
            return None  # 用户名不存在
        # 验证密码
        if bcrypt.checkpw(password.encode('utf-8'), admin["password"]):
            return admin  # 验证成功
        return None